package com.tanhua.api;

import com.tanhua.sso.pojo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@DubboService
public class VisitorsServiceApiImpi implements VisitorsServiceApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    //更新或添加来访,一天只有一条来访记录
    @Override
    public void save(Visitors visitors) {
        Criteria criteria = Criteria.where("userId").is(visitors.getId()).and("visitorUserId").is(visitors.getVisitorUserId()).and("visitDate").is(visitors.getVisitDate());
        //查找是否有符合条件的数据
        boolean exists = mongoTemplate.exists(Query.query(criteria), Visitors.class);

        //没有则新增
        if (!exists&&visitors.getVisitorUserId()!=visitors.getUserId()){
            mongoTemplate.save(visitors);
        }
    }

    //第一次查看是否被来访
    @Override
    public List<Visitors> selectVisitors(Long userId, long timeMillis) {
        Criteria lt = Criteria.where("userId").is(userId);
        List<Visitors> visitorsList = mongoTemplate.find(Query.query(lt).limit(5).with(Sort.by(Sort.Order.desc("date"))), Visitors.class);
        List<Visitors> collect = visitorsList.stream().filter(visitors -> visitors.getVisitorUserId() != visitors.getUserId()).collect(Collectors.toList());
        return collect;
    }

    //再次
    @Override
    public List<Visitors> selectVisitor(Long userId, long timeMillis) {
        Criteria lt = Criteria.where("userId").is(userId).and("date").gt(timeMillis);
        List<Visitors> visitorsList = mongoTemplate.find(Query.query(lt).limit(5).with(Sort.by(Sort.Order.desc("date"))), Visitors.class);
        List<Visitors> collect = visitorsList.stream().filter(visitors -> visitors.getVisitorUserId() != visitors.getUserId()).collect(Collectors.toList());
        return collect;
    }


    /*我的访客*/
    @Override
    public List<Visitors> myVisitorUserId(Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        List<Visitors> visitorsList = mongoTemplate.find(Query.query(criteria).with(Sort.by(Sort.Order.desc("date"))), Visitors.class);
        List<Visitors> collect = visitorsList.stream().filter(visitors -> visitors.getVisitorUserId() != visitors.getUserId()).collect(Collectors.toList());
        return collect;
    }
}
